# Copyright (c) 2022 Presto Labs Pte. Ltd.
# Author: gekim

import requests
from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo
from time import sleep

def generate():
  mea = 'Spot.Coingecko.v3'
  me = 'Spot.Coingecko'
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()

  symbol_set = set()
  pis = []
  for i in range(1, 5):
    # It refers to 
    # "cc/coin2/exchange/coingecko/feed_v3/symbol_updater.h"
    data = requests.get(
      'https://api.coingecko.com/api/v3/coins/'
      'markets?'
      'vs_currency=usd&'
      'order=market_cap_desc&'
      'per_page=250&page=%d&'
      'sparkline=false' % i
      ).json()

    for info in data:
      native_symbol = info['id']
      native_base = native_symbol
      native_quote = 'USD'
      base = info['symbol'].upper()
      base = symbol_info.native_to_norm_currency(mea, base)
      quote = 'USD'
      symbol = f"%s-%s" % (base, quote)

      if len(symbol.split("-")) > 2:
        print("{}, filter symbol: {}".format(mea, symbol))
        continue

      pi = dict(
          symbol=symbol,
          base=base,
          quote=quote,
          native_symbol=native_symbol,
          native_base=native_base,
          native_quote=native_quote,
          price_ticksize=0,
          qty_ticksize=0
      )
      pi = {**pi, **default.product_info(me, symbol)}
      if pi["symbol"] not in symbol_set:
        symbol_set.add(pi["symbol"])
        pis.append(pi)
    # avoid hit rate limit
    sleep(20)

  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis


def gen_coin1_constants():
  data = generate()
  data = convert_coin1_constants(data)
  return data


def convert_coin1_constants(data):
  quote_currency_list = [info['native_quote'].upper() for info in data]
  base_currency_list = [info['native_base'].upper() for info in data]
  currency_list = base_currency_list + quote_currency_list
  symbol_list = [info['native_symbol'].lower().replace('-', '_') for info in data]
  return {
      'quote_currency_list': list(set(quote_currency_list)),
      'currency_list': list(set(currency_list)),
      'symbol_list': list(set(symbol_list)),
  }


if __name__ == "__main__":
  print(generate())
